import xlwt, copy

class XLS:
    instance = None
    def __new__(cls, **kwargs):
        if cls.instance is None:
            cls.instance = super().__new__(cls,**kwargs)
            cls.workbook = xlwt.Workbook()
        return cls.instance
    
    @classmethod
    def new_book(cls):
        cls.workbook = xlwt.Workbook()
    
    def __init__(self, **kwargs):
        '''
            配置一个简单的写表格类
        '''
        self.style = xlwt.XFStyle()
        self.style.alignment.wrap = 1 
        self.style.alignment.horz = 0
        self.style.alignment.vert = 1
        self.title_style = copy.deepcopy(self.style)
        ft = xlwt.Font()
        # ft.name = "Times New Roman"
        # self.style.font = copy.deepcopy(ft)
        ft.bold = True 
        ft.colour_index = 1
        pattern = xlwt.Pattern()
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern.pattern_fore_colour = xlwt.Style.colour_map["blue_gray"]
        self.title_style.pattern = pattern
        self.title_style.font = ft

        if "width" in kwargs:
            width = kwargs.pop("width")
        else:
            width = 5000
        self.width = width
    
    def write_table(self, sheetname, title, datas, width=None):
        sheet = self.workbook.add_sheet(sheetname)
        for i in range(len(title)):
            sheet.col(i).width = self.width
        if width:
            for i in width:
                sheet.col(i[0]).width = i[1]
        # 写标题
        for i, text in enumerate(title):
            sheet.write(0, i, text, self.title_style)
        # 写数据
        for i, cells in enumerate(datas):
            for j, text in enumerate(cells):
                sheet.write(i+1, j, text, self.style)
        return sheet
    
    def save(self, path):
        self.workbook.save(path)
